#! /usr/bin/python3.7
# -*- coding: utf-8 -*-
import json, time, requests
import RPi.GPIO as GPIO
import Adafruit_DHT

# GPIO通道（BCM编号）定义，MQ-135=21，DHT11：4
SMOKE_SENSOR_CHANNEL = 21
SMOKE_GPIO = GPIO
TEMP_RH_SENSOR_CHANNEL = 4
# 初始化记录时间
recordTime = 0
# 后端地址
SERVER_URL = "http://106.13.136.240:12333"
HEADERS = {
    'Content-Type': 'application/json'
}
# 上报数据模板
template = {"temperature": 0.0, "humidity": 0.0, "gas": 0}
# 预设阈值[温度，湿度]
warning_value = [35.0, 60]
# 初始化记录时间
record_time = 0
# 记录缓存[温度，湿度，有害气体]
record_cache = [0.0, 0.0, 0]


# 上报正常数据的周期
def check_time_period(curr_time):
    thisTime = int(round(time.time() * 1000))
    # 距离上次记录时间已经超过或等于2分钟
    if curr_time + 60000 <= thisTime:
        return True
    else:
        return False


# 初始化MQ-135的GPIO对象及对应参数（GPIO引脚通道、针脚模式，初始化低电平）
def init_smoke():
    SMOKE_GPIO.setmode(GPIO.BCM)
    SMOKE_GPIO.setup(SMOKE_SENSOR_CHANNEL, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    return SMOKE_GPIO


# 上报数据的方法
# 如果有异常数据，立刻上传
# 如果无异常数据，每X分钟上传一次
# 如果本次上传数据与上次已上传的重复，则不上传
def do_post(temper, humi, smoke):
    if temper == record_cache[0] and humi == record_cache[1] and smoke == record_cache[2]:
        print("跳过该条数据")
        return int(round(time.time() * 1000))
    toPost = template
    toPost['temperature'] = temper
    toPost['humidity'] = humi
    toPost['gas'] = smoke
    post_url = SERVER_URL + "/api/sensor/insertSensorData"
    requests.request("POST", post_url, headers=HEADERS, data=json.dumps(toPost))
    record_cache[0] = temper
    record_cache[1] = humi
    record_cache[2] = smoke
    print("上传一条数据", toPost)
    return int(round(time.time() * 1000))


if __name__ == '__main__':
    SMOKE_GPIO_INSTANCE = init_smoke()
    while True:
        try:
            humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 4)
            status_smoke = SMOKE_GPIO_INSTANCE.input(SMOKE_SENSOR_CHANNEL)
            if temperature >= warning_value[0] or humidity >= warning_value[1] or status_smoke == 0:
                print("超标传值")
                record_time = do_post(temperature, humidity, status_smoke)
            elif check_time_period(record_time):
                print("超时传值")
                record_time = do_post(temperature, humidity, status_smoke)
            else:
                continue
        except Exception as exp:
            print("Exception:", exp)
        finally:
            time.sleep(1)
